package cn.zymall.common.utils.elsearch;

import cn.zymall.common.model.Spu;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author xuxianda
 * @Description: ElasticSearch工具类
 * @date 2020/8/20 21:07
 * @Copyright
 * @return
 **/
@Component
public class ElSearchUtil {

    @Autowired
    private ElasticsearchRestTemplate esRestTemplate;

    /**
     * 搜索功能
     *  注意： 传入的实体类必须 在类上使用@Document注解 详情参考实体类‘Spu’
     * @param fieldName 字段名称
     * @param keyword 搜索内容
     * @param clazz 实体类
     * @param pageable 分页
     * @return List 结果集合
     */
    public List select(String fieldName, String keyword, Class clazz, Pageable pageable) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery(fieldName, keyword)).withPageable(pageable)
                .build();
        SearchHits<Spu> search = esRestTemplate.search(searchQuery, clazz);
        search.get().forEach(item -> {
            System.out.println(item.getContent());
        });
        Object[] objects = search.get().toArray();
        ArrayList arrayList = new ArrayList<>(objects.length);
        Collections.addAll(arrayList, objects);
        return arrayList;
    }
}
